package com.hao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hao.entity.SensorData;
import com.hao.mapper.SensorDataMapper;
import com.hao.service.SensorDataService;
import com.hao.util.DataValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 传感器数据服务实现类
 */
@Slf4j
@Service
public class SensorDataServiceImpl extends ServiceImpl<SensorDataMapper, SensorData> implements SensorDataService {
    
    private static final Logger rawDataLogger = LogManager.getLogger("com.hao.rawdata");
    private static final Logger errorLogger = LogManager.getLogger("com.hao.error");
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchSave(List<String> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            log.warn("数据列表为空，跳过保存");
            return 0;
        }
        
        // 记录原始数据到日志文件
        for (String dataString : dataList) {
            rawDataLogger.info("接收到原始数据: {}", dataString);
        }
        
        List<SensorData> sensorDataList = new ArrayList<>();
        
        for (String dataString : dataList) {
            try {
                // 数据格式验证
                DataValidator.ValidationResult validationResult = DataValidator.validateData(dataString);
                if (!validationResult.isValid()) {
                    log.warn("数据格式验证失败: {}", validationResult.getMessage());
                    errorLogger.error("数据格式验证失败: {} - 数据: {}", validationResult.getMessage(), dataString);
                    continue;
                }
                
                // 创建传感器数据对象
                SensorData sensorData = new SensorData(dataString);
                sensorDataList.add(sensorData);
                
            } catch (Exception e) {
                log.error("解析数据时发生错误: {}, 数据: {}", e.getMessage(), dataString);
                errorLogger.error("解析数据时发生错误: {} - 数据: {}", e.getMessage(), dataString);
            }
        }
        
        if (sensorDataList.isEmpty()) {
            log.warn("没有有效的数据需要保存");
            return 0;
        }
        
        try {
            // 使用MyBatis-Plus的批量保存方法
            boolean success = super.saveBatch(sensorDataList);
            if (success) {
                log.info("成功保存 {} 条传感器数据", sensorDataList.size());
                return sensorDataList.size();
            } else {
                log.error("保存传感器数据失败");
                errorLogger.error("保存传感器数据失败，数据条数: {}", sensorDataList.size());
                return 0;
            }
        } catch (Exception e) {
            log.error("批量保存传感器数据时发生异常: {}", e.getMessage(), e);
            errorLogger.error("批量保存传感器数据时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    public boolean save(SensorData sensorData) {
        if (sensorData == null) {
            log.warn("传感器数据为空，跳过保存");
            return false;
        }
        
        try {
            boolean success = super.save(sensorData);
            if (success) {
                log.info("成功保存传感器数据: {}", sensorData);
            } else {
                log.error("保存传感器数据失败: {}", sensorData);
                errorLogger.error("保存传感器数据失败: {}", sensorData);
            }
            return success;
        } catch (Exception e) {
            log.error("保存传感器数据时发生异常: {}", e.getMessage(), e);
            errorLogger.error("保存传感器数据时发生异常: {}", e.getMessage(), e);
            return false;
        }
    }
} 